import game
import sprite
import vector


def next_id():
	return len(Thing.group)


class Thing(sprite.Sprite):

	group = sprite.Group()

	def __init__(self, id, owner, health, location, size, target):
		self.id = id
		sprite.Sprite.__init__(self, Thing.group, self.group)
		self.owner = sprite.GroupSingle(owner)
		self.health = health
		self.location = location
		self.size = size
		self.target = sprite.GroupSingle(target)
		self.weapons = [w() for w in self.weapons]
		self.last_color = None

	@property
	def center(self):
		c = vector.Vec3(*self.location)
		c.z += 0.5 * self.size
		return c

	def damage(self, health):
		self.health -= health

	def draw(self):
		for weapon in self.weapons:
			weapon.draw()

	def on_thing_state_update(self, owner, health, location, size, target):
		if owner is not None:
			self.owner.add(owner)
		if health is not None:
			self.health = health
		if location is not None:
			self.location = location
		if size is not None:
			self.size = size
		if target is not None:
			self.target.add(target)

	def update_color(self):
		if self in game.local_player.selected:
			color = [c+.2 for c in self.color]
		else:
			color = self.color
		if color != self.last_color:
			self.vertex_list.colors = color * (len(self.vertex_list.vertices) / 3)
			self.last_color = color

	def on_update(self, dt):
		if self.weapons:
			# targeting
			# FIXME automatically targets nearest non-owned unit or building
			nearest = None
			for a in Thing.group:
				if not set(self.owner.sprites()).intersection(set(a.owner.sprites())):
					distance = (a.location - self.location).length()
					if nearest is None or distance < nearest:
						nearest = distance
						self.target.add(a)

			# weapons
			for weapon in self.weapons:
				weapon.update(dt)
				if self.target:
						weapon.fire(self, self.target)

